package com.lai.hospital.filter;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.lai.hospital.constant.SecurityConst;
import com.lai.hospital.service.impl.UserDetailsServiceImpl;
import com.lai.hospital.utils.JwtTokenUtils;
import com.lai.hospital.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.lai.hospital.constant.SecurityConst.TOKEN_FAILURE;

/**
 * @description: 校验请求，判断是否已经登录
 * 已登录：保存用户信息
 * 未登录：不处理
 * @author: laiciqi
 * @create: 2022-09-13 16:59
 **/
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String token = request.getHeader(SecurityConst.TOKEN_HEADER);//获取请求头的Authorization中的参数
        if (token == null) {//如果token为空或者不是以指定前缀开始
            SecurityContextHolder.clearContext();//清空上下文

        } else {
            DecodedJWT decodedJWT = null;
            try {
                decodedJWT = jwtUtils.verify(token);
            } catch (SignatureVerificationException e) {
                e.printStackTrace();
//                error = R.error("无效签名！");
            } catch (TokenExpiredException e) {
                e.printStackTrace();
//                error = R.error("token过期！");
            } catch (AlgorithmMismatchException e) {
                e.printStackTrace();
//                error = R.error("token算法不一致！");
            } catch (Exception e) {
                e.printStackTrace();
//                error = R.error("token无效！");
            }

            if (decodedJWT != null && StringUtils.isNotBlank(JwtUtils.getUserName(decodedJWT))) {
                // Token 校验通过
                UserDetails userDetails = this.userDetailsService.loadUserByUsername(JwtUtils.getUserName(decodedJWT));
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());

                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(
                        request));

                SecurityContextHolder.getContext().setAuthentication(authentication);
            }

        }
        filterChain.doFilter(request, response);
    }
}
